<template>
  <div class="sales-prediction-container">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="logo">
        <div class="logo-icon">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="logo-text">NEWBE工作室</div>
      </div>
      
      <ul class="nav-items">
        <li class="nav-item">
          <router-link to="/rfm-analysis" class="nav-link">RFM客户行为分析</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/customer-lifecycle" class="nav-link">客户生命周期</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/marketing-analysis" class="nav-link">营销活动分析</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/sales-prediction" class="nav-link active">销售预测</router-link>
        </li>
      </ul>
      
      <div class="user-profile">
        <div class="user-avatar">{{ userInfo.nickname?.charAt(0)?.toUpperCase() || 'A' }}</div>
      </div>
    </nav>

    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button 
        class="back-button" 
        type="primary" 
        size="small" 
        @click="goBack"
      >
        <el-icon><Back /></el-icon>
        返回工作台
      </el-button>
    </div>

    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="title-section">
          <h1>销售预测分析</h1>
          <p class="subtitle">基于历史数据分析和多种算法的销售趋势预测</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" :icon="Download" @click="exportReport">
            导出报告
          </el-button>
          <el-button :icon="Refresh" @click="refreshData">
            刷新数据
          </el-button>
        </div>
      </div>
      
      <!-- 介绍卡片 -->
      <div class="info-card">
        <div class="info-card-icon">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="info-card-content">
          <h3>销售预测系统</h3>
          <p>本系统基于历史销售数据，使用多种算法模型对未来销售额进行预测。可用于业务规划、库存管理和营销决策支持。</p>
        </div>
      </div>
      
      <!-- 预测概览 -->
      <prediction-overview 
        :prediction-data="predictionData"
        :loading="loadingPrediction"
        @method-change="handleMethodChange"
      />
      
      <!-- 两栏图表 -->
      <div class="charts-row">
        <sales-trend-chart 
          :sales-data="predictionData.sales_data || []"
          :prediction="predictionData.prediction"
          :upper-bound="predictionData.upper_bound"
          :lower-bound="predictionData.lower_bound"
          :next-month="predictionData.next_month"
          :loading="loadingPrediction"
        />
        <seasonality-chart 
          :seasonality-data="seasonalityData.seasonality_data || []"
          :loading="loadingSeasonality"
        />
      </div>
      
      <!-- 产品对比和误差分析 -->
      <div class="charts-row">
        <product-comparison
          :product-data="productComparisonData.product_comparison || []"
          :loading="loadingProductComparison"
        />
        <error-analysis />
      </div>
      
      <!-- 历史销售数据表格 -->
      <historical-sales-table
        :sales-data="historicalSalesData.sales_data || []"
        :loading="loadingHistoricalData"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, Refresh, TrendCharts, DataAnalysis, Back } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import { 
  predictSales, 
  getHistoricalSales, 
  getSalesSeasonality,
  getProductSalesComparison
} from '@/api/sales-prediction';

// 导入子组件
import PredictionOverview from './components/PredictionOverview.vue';
import SalesTrendChart from './components/SalesTrendChart.vue';
import SeasonalityChart from './components/SeasonalityChart.vue';
import ProductComparison from './components/ProductComparison.vue';
import ErrorAnalysis from './components/ErrorAnalysis.vue';
import HistoricalSalesTable from './components/HistoricalSalesTable.vue';

// 获取用户信息
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);

// 数据状态
const predictionData = ref({});
const historicalSalesData = ref({});
const seasonalityData = ref({});
const productComparisonData = ref({});

// 加载状态
const loadingPrediction = ref(true);
const loadingHistoricalData = ref(true);
const loadingSeasonality = ref(true);
const loadingProductComparison = ref(true);

// 默认预测方法
const predictionMethod = ref('moving_average');

// 初始化数据
onMounted(async () => {
  console.log('SalesPrediction组件挂载');
  
  await Promise.all([
    loadPredictionData(),
    loadHistoricalData(),
    loadSeasonalityData(),
    loadProductComparison()
  ]);
});

// 加载销售预测数据
async function loadPredictionData() {
  try {
    loadingPrediction.value = true;
    const result = await predictSales({
      method: predictionMethod.value,
      months: 12
    });
    predictionData.value = result;
  } catch (error) {
    console.error('加载销售预测数据失败', error);
    ElMessage.error('加载销售预测数据失败');
  } finally {
    loadingPrediction.value = false;
  }
}

// 加载历史销售数据
async function loadHistoricalData() {
  try {
    loadingHistoricalData.value = true;
    const result = await getHistoricalSales({ months: 24 });
    historicalSalesData.value = result;
  } catch (error) {
    console.error('加载历史销售数据失败', error);
    ElMessage.error('加载历史销售数据失败');
  } finally {
    loadingHistoricalData.value = false;
  }
}

// 加载季节性分析数据
async function loadSeasonalityData() {
  try {
    loadingSeasonality.value = true;
    const result = await getSalesSeasonality();
    seasonalityData.value = result;
  } catch (error) {
    console.error('加载季节性分析数据失败', error);
    ElMessage.error('加载季节性分析数据失败');
  } finally {
    loadingSeasonality.value = false;
  }
}

// 加载产品销售对比数据
async function loadProductComparison() {
  try {
    loadingProductComparison.value = true;
    const result = await getProductSalesComparison();
    productComparisonData.value = result;
  } catch (error) {
    console.error('加载产品销售对比数据失败', error);
    ElMessage.error('加载产品销售对比数据失败');
  } finally {
    loadingProductComparison.value = false;
  }
}

// 处理预测方法变更
function handleMethodChange(method) {
  predictionMethod.value = method;
  loadPredictionData();
}

// 刷新所有数据
function refreshData() {
  ElMessage.info('正在刷新数据...');
  Promise.all([
    loadPredictionData(),
    loadHistoricalData(),
    loadSeasonalityData(),
    loadProductComparison()
  ]).then(() => {
    ElMessage.success('数据已刷新');
  });
}

// 导出报告功能
function exportReport() {
  ElMessageBox.confirm(
    '确定要导出销售预测分析报告？',
    '导出确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.success('报告导出成功');
  }).catch(() => {});
}

// 返回工作台
function goBack() {
  window.location.href = 'dashboard#/dashboard';
}
</script>

<style scoped>
.sales-prediction-container {
  padding: 0;
  color: var(--text-color, #e0e0ff);
  background-color: var(--dark-bg, #0d0e1a);
  min-height: 100vh;
}

/* 导航栏样式 */
.navbar {
  background-color: var(--card-bg, #13142a);
  padding: 0.8rem 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  position: sticky;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--border-color, #2a2a57);
}

.logo {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background: var(--gradient-primary, linear-gradient(135deg, #3a36db, #00c9ff));
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  box-shadow: 0 4px 15px rgba(58, 54, 219, 0.3);
}

.logo-text {
  font-size: 1.2rem;
  font-weight: 600;
  background: var(--gradient-primary, linear-gradient(135deg, #3a36db, #00c9ff));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.nav-items {
  display: flex;
  gap: 2.5rem;
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-item {
  list-style: none;
  position: relative;
}

.nav-link {
  color: var(--text-color, #e0e0ff);
  text-decoration: none;
  font-size: 1rem;
  font-weight: 500;
  padding: 0.5rem 0;
  transition: all 0.3s ease;
}

.nav-link.active {
  color: var(--secondary-color, #00ffb3);
  font-weight: 600;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 100%;
  height: 3px;
  background: var(--gradient-secondary, linear-gradient(135deg, #00e1d9, #00ffb3));
  border-radius: 3px;
}

.nav-link:hover {
  color: var(--secondary-color, #00ffb3);
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background: var(--gradient-primary, linear-gradient(135deg, #3a36db, #00c9ff));
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(58, 54, 219, 0.3);
}

/* 页面内容区样式 */
.page-content {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h1 {
  margin: 0;
  font-size: 24px;
  background: var(--gradient-primary, linear-gradient(135deg, #3a36db, #00c9ff));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 600;
}

.subtitle {
  margin: 5px 0 0;
  font-size: 14px;
  color: var(--text-tertiary, #7171a6);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.info-card {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--bg-card, #13142a);
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  border: 1px solid var(--border-color, #2a2a57);
}

.info-card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--gradient-primary, linear-gradient(135deg, #3a36db, #00c9ff));
  width: 48px;
  height: 48px;
  border-radius: 12px;
  margin-right: 16px;
  flex-shrink: 0;
}

.info-card-icon .el-icon {
  font-size: 24px;
  color: #fff;
}

.info-card-content h3 {
  margin: 0 0 5px;
  font-size: 18px;
  font-weight: 600;
}

.info-card-content p {
  margin: 0;
  color: var(--text-secondary, #b8b8cc);
  font-size: 14px;
  line-height: 1.5;
}

.charts-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
  height: 450px; /* 固定图表行的高度 */
}

.charts-row > * {
  min-height: 0; /* 防止子元素溢出 */
  height: 100%; /* 让子元素填充行高 */
  overflow: hidden; /* 确保没有溢出 */
}

@media (max-width: 1200px) {
  .charts-row {
    grid-template-columns: 1fr;
    height: auto; /* 在小屏幕上允许自动高度 */
  }
  
  .charts-row > * {
    height: 450px; /* 在小屏幕上给每个图表一个固定高度 */
    margin-bottom: 20px;
  }
}

/* 添加返回按钮样式 */
.back-button-container {
  padding: 12px 24px;
  background-color: var(--bg-card, #13142a);
  border-bottom: 1px solid var(--border-color, #2a2a57);
}

.back-button {
  display: flex;
  align-items: center;
  gap: 6px;
  background: linear-gradient(135deg, #3a36db, #00c9ff);
  border: none;
  padding: 6px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(58, 54, 219, 0.3);
}

.back-button:hover {
  box-shadow: 0 4px 12px rgba(58, 54, 219, 0.5);
  transform: translateY(-2px);
}
</style> 